package com.demo.minademo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

import java.util.logging.Logger;

public class DefaultHandler extends IoHandlerAdapter {

    public static final String TAG = "DefaultHandler";
    public static final String BROADCAST_ACTION = "com.demo.mina";
    public static final String MSG = "message";
    private Context mContext;
    public DefaultHandler(Context context){
        this.mContext = context;
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        super.sessionOpened(session);
        Log.e(TAG,"sessionId = " + session.getId());
        //将session保存到session manager,从而可以发送消息到服务器
        SessionManager.getInstance().setSession(session);
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        super.messageReceived(session, message);
        if(mContext != null){
            System.out.println(message.toString());

            Intent intent = new Intent(BROADCAST_ACTION);
            intent.putExtra(MSG,message.toString());
            LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
        }
    }
}
